import { useEffect, useState } from 'react';
import { Button, Spin, Tabs, message, Switch } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { ContractWarnTabsPane } from './ContractWarnTabsPane';
import Cls from 'classnames';
import InfiniteScroll from 'react-infinite-scroller';
import '../common/styles.less';
import pageStyles from '@/common/pageLayout.less';
import { handleDataGridService } from '../services';

export const ContractWarnView: React.FC<ContractWarnsHomePageAPI.IContractWarnView> = ({ curRes }) => {
  /** 样式根目录 */
  const styleFixCls = 'contract-warn';

  /** 存入选中的tab标识 */
  const [tabPaneKey, setTabPaneKey] = useState<string>('');

  /** 保存合同预警数据 */
  const [manageDataList, setManageDataList] = useState<Record<string, any>[]>([]);

  /** 已读未读 */
  const [readFlagSwitch, setReadFlagSwitch] = useState<string>('0');

  /** 保存的分页参数 */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 0,
    loading: false,
    hasMore: true,
    limit: 10,
  });

  /**
   * 初始化获取数据
   */
  const defaultGetWarnData = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,
      count: count,
      loading: true,
    });
    let payload = {
      page: 1,
      rows: count * 10 + limit,
      readFlag: readFlagSwitch,
      handleStyle: tabPaneKey,
    };
    handleDataGridRun(payload);
  };

  useEffect(() => {
    if (tabPaneKey && readFlagSwitch) {
      defaultGetWarnData();
    }
  }, [tabPaneKey, readFlagSwitch]);

  useEffect(() => {
    if (curRes?.['/contractController/handleHomePage']) {
      setTabPaneKey('0');
    } else if (curRes?.['/contractController/notifyHomePage']) {
      setTabPaneKey('1');
    }
  }, [curRes]);

  /** 处理滚动加载 */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (manageDataList?.length >= total) {
      message.warning('没有更多数据了哦');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetWarnData();
  };

  /** 刷新回调 */
  const reloadHomeCallback = () => {
    setScrollObj({
      ...scrollObj,
      count: 0,
    });
    defaultGetWarnData();
  };

  const supervisingCallback = (res: any) => {
    if (res && res?.msgFlag) {
      setManageDataList(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        total: res.total,
      });
    } else {
      message.error(res?.msg);
    }
  };

  const { handleDataGridRun, handleDataGridLoading, manageSearchParams } = handleDataGridService(curRes, supervisingCallback);

  /** 提醒状态切换 */
  const SupervisingSta = (state) => {
    setScrollObj({
      total: 0,
      count: 0,
      loading: false,
      hasMore: true,
      limit: 10,
    });
    setReadFlagSwitch(state ? '0' : '1');
  };

  /** 刷新 */
  const tabsExtraBtns = () => {
    return (
      <div className={`${styleFixCls}-tabRead`}>
        <Switch
          // checkedChildren="已读"
          // unCheckedChildren="未读"
          checkedChildren={<span style={{ color: '#ff0000' }}>未读</span>}
          unCheckedChildren={<span style={{ color: '#52c41a' }}>已读</span>}
          onClick={SupervisingSta}
          checked={manageSearchParams?.readFlag == '0' ? true : false}
        />
        &nbsp;&nbsp;
        <Button type="primary" icon={<ReloadOutlined />} onClick={reloadHomeCallback} />
      </div>
    );
  };

  /** 提醒事项tabItem切换 */
  // const tabsItem = [
  //   {

  //   }, // 务必填写 key
  // ];

  const tabsItem = () => {
    let tabsConfig: any[] = [];
    if (curRes?.['/contractController/handleHomePage']) {
      tabsConfig?.push({
        label: '提醒事项',
        key: '0',
        children: (
          <div className={pageStyles['InfiniteScrollView']}>
            <InfiniteScroll
              loadMore={handleInfiniteOnLoad}
              initialLoad={false}
              pageStart={1}
              useWindow={false}
              hasMore={!scrollObj?.loading && scrollObj?.hasMore}
            >
              <ContractWarnTabsPane
                styleClassName={styleFixCls}
                contractInfoList={manageDataList}
                // reloadManage={reloadRefresh}
                reloadManage={() => {
                  defaultGetWarnData();
                }}
                curRes={curRes}
                tabPaneKey={tabPaneKey}
              />
            </InfiniteScroll>
          </div>
        ),
      });
    }
    if (curRes?.['/contractController/notifyHomePage']) {
      tabsConfig?.push({
        label: '消息通知',
        key: '1',
        children: (
          <div className={pageStyles['InfiniteScrollView']}>
            <InfiniteScroll
              loadMore={handleInfiniteOnLoad}
              initialLoad={false}
              pageStart={1}
              useWindow={false}
              hasMore={!scrollObj?.loading && scrollObj?.hasMore}
            >
              <ContractWarnTabsPane
                styleClassName={styleFixCls}
                contractInfoList={manageDataList}
                // reloadManage={reloadRefresh}
                reloadManage={() => {
                  defaultGetWarnData();
                }}
                curRes={curRes}
                tabPaneKey={tabPaneKey}
              />
            </InfiniteScroll>
          </div>
        ),
      });
    }
    return tabsConfig;
  };

  return (
    <div className={Cls(`${styleFixCls}`, pageStyles['commonTabsLine'])}>
      <Spin spinning={handleDataGridLoading}>
        <Tabs
          activeKey={tabPaneKey}
          tabBarExtraContent={tabsExtraBtns()}
          items={tabsItem()}
          onChange={(activeKey: string) => {
            setScrollObj({
              total: 0,
              count: 0,
              loading: false,
              hasMore: true,
              limit: 10,
            });
            setTabPaneKey(activeKey);
            // defaultGetWarnData()
          }}
        />
      </Spin>
    </div>
  );
};
